import {
    msg,
    close
} from '../../common/utils.js';
import Vue from 'vue';
import {
    serverPath,
    json,
    currentPath
} from '../../common/config.js';
import IconsService from '../services/iconsService.js';
import FileService from '../services/fileService.js';

window.Module = function () {
    let iconsService = new IconsService();
    let fileService =new FileService();
    return new Vue({
        el: '#addPageController',
        data: {
            entity: {

            },
            fileName:''
        },
        methods: {
            add: async function () {
                if (!validator.checkAll('form')) {
                    layer.msg('请填写正确参数');
                    return;
                }
                let res = await iconsService.createIcons(this.entity);
                if (!res.type) {
                    for (var item in res) {
                        msg(res[item][0]);
                        break;
                    }
                }
                else{
                    var response = res.body;
                    if('Success' == response.result){
                        this.close();
                    }
                    else{
                        msg(response.message);
                    }
                }
            },
            close: function () {
                close();
            },
            selectFile: function () {
                $('#file').click();
            },
            selectedFile: async function (e) {
                var file = $(e.target)[0].files[0];
                if (file) {
                    this.fileName = file.name;

                    let res = await fileService.uploadFile(file);
                    if ('application/json' == res.type) {
                        console.log(res);
                        var response = res.body;
                        if ('Success' == response.result) {
                            var src = $('#preview').attr('src');
                            this.entity.imgPath = response.data;
                            if (src)
                                await fileService.deleteFile    (src);
                            $('#preview').attr('src', response.data);
                        } else {
                            await msg(response.message);
                        }
                    } else {
                        await msg('不能链接服务器');
                    }
                }
            },
            preview: async function () {
                var src = $('#preview').attr('src');
                let options = {
                    title: "预览",
                    content: `<img src=${src} />`,
                    type: 1,
                    shadeClose: true,
                    shade: 0.8,
                    maxmin: false,
                    area: false
                };
                await open(options);
            }
        }
    });
}